package com.gitee.adapter;

import com.alibaba.fastjson.JSONObject;
import com.gitee.pojo.UserInfo;
import com.gitee.service.UserService;
import com.gitee.utils.HttpClientUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 用户登录  第三方登录 适配器模式（类适配器模式）
 *
 * @author acao
 * @since 2023-11-06 09:56
 */
@Slf4j
@Component
public class Login3rdAdapter extends UserService implements Login3rdTarget {

    @Value("${gitee.state}")
    private String giteeState;

    @Value("${gitee.token.url}")
    private String giteeTokenUrl;

    @Value("${gitee.user.url}")
    private String giteeUserUrl;

    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;

    /**
     * gitee第三方登录
     *
     * @param code code
     */
    @Override
    public String giteeLogin(String code) {

        //gitee 登录返回code 更具code获取token
        String getTokenUrl = giteeTokenUrl.concat(code);
        JSONObject tokenJson = HttpClientUtils.execute(getTokenUrl, HttpMethod.POST);
        String token = String.valueOf(tokenJson.get("access_token"));
        System.out.println(token);

        //更具token获取用户信息
        String getUserInfoUrl = giteeUserUrl.concat(token);
        JSONObject userInfoJson = HttpClientUtils.execute(getUserInfoUrl, HttpMethod.GET);
        log.info("----------------------------------->UserinfiJson={}", userInfoJson);

        //获取用户信息，userName添加前缀 GITEE@, 密码保持与userName一致。讨论过程请参见2.3小节
        String userName = giteeUserPrefix.concat(String.valueOf(userInfoJson.get("name")));
        String password = userName;

        return autoRegister3rdAndLogin(userName, password);
    }

    private String autoRegister3rdAndLogin(String userName, String password) {
        //如果第三方账号已经登录过，则直接登录
        if (super.checkUserExists(userName)) {
            return super.login(userName, password);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userInfo.setCreateDate(new Date());

        //如果第三方账号是第一次登录，先进行“自动注册”
        super.register(userInfo);
        //自动注册完成后，进行登录
        return super.login(userName, password);
    }

    @Override
    public String wechatLogin(String code) {
        return null;
    }

    @Override
    public String QQLogin(String code) {
        return null;
    }
}
